package cn.com.cfae.iras.doc.analyze.components.integrity;

import cn.com.cfae.iras.doc.analyze.beans.web.ContentAndPosition;
import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import cn.com.cfae.iras.doc.analyze.parse.model.PageModel;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * Created by 佟媛媛 on 18/10/23.
 */

@Component("I1010")
@Scope("prototype")
public class I1010 extends BaseComponent {

    private static Logger log = LoggerFactory.getLogger(I1010.class);

    @Autowired
    private I1001 i1001;

    /**
     * @auth 佟媛媛
     * @date 18/10/29 下午7:13
     * @desc
     * 检查募集说明书中是否含有“在建工程”、“投资金额”、“已投资金额”、“合规性”、“自有资本金”、“拟建工程”关键词。
     * 若未披露相应关键词，提示具体未披露哪个关键词。
     * "1、如果在建工程为无，不进行后续判断；
    1.1、在建工程检查“投资金额”、“已投资金额”、“资本金”、“合规性”；
    1.2、项目总投资额占比10%以上，没有提示合计，（每项投资额/投资总额）获取占比，大于10%以上，需要项目情况介绍，项目投资额从表格抽取；
    1.3、项目建设情况介绍，检查行数>=3行；
    2、拟建：投资金额，（投资计划|投资进度安排)
    2.1、如果拟建工程为无，不进行后续判断；
    5、本规则不涉及已完成工程；"

    是否引用
     */
    @Override
    public List<ComponentResult> handlerM() {
        return common("M-5");
    }

    private List<ComponentResult> common(String catalogId){
        List<ComponentResult> list = new ArrayList<>();
        setCatalogId(catalogId);
        Map<String,String> ZJGCMap = new HashMap();
        double ZTZJE = 0;
        int pageNum = getChapterModel(getCatalogId()).getStartPage();
        ExtractBizModel model = getModel(getCatalogId(),"ZJGC");
        List<Map<String, ExtractItem>> zjgcTable = model.getTables3();
        if(!CollectionUtils.isEmpty(zjgcTable)){
            for(Map<String, ExtractItem> entry : zjgcTable){
                ExtractItem value = entry.get("TZJE");
                if(value!=null){
                    KVText TZJE = value.getValue();//投资金额
                    if(TZJE!=null){
                        ZTZJE += getDouble(TZJE.getText());
                    }
                }
            }
            for(Map<String, ExtractItem> entry : zjgcTable){
                ExtractItem XMMC = entry.get("XMMC");//项目名称
                ExtractItem TZJE = entry.get("TZJE");//投资金额
                ExtractItem YTZJE = entry.get("YTZJE");//已投资金额
                ExtractItem ZBJ = entry.get("ZBJ");//资本金
                ExtractItem HGX = entry.get("HGX");//合规性
                String projectName = XMMC!=null&&XMMC.getValue()!=null?XMMC.getValue().getText():"";
                if(!StringUtils.isEmpty(projectName) && !"项目名称".equals(projectName)){
                    projectName = projectName.replace("\n","").replace("\r","");
                    if(TZJE==null || TZJE.getKey()==null || StringUtils.isEmpty(TZJE.getKey().getText())){
                        ComponentResult zjgc = getComponentResult(true,"02","在建工程检查（"+projectName+"）",pageNum,"投资金额缺失",getRuleTitle(),null);
                        list.add(zjgc);
                    }else{
                        int _pageNum = CollectionUtils.isEmpty(TZJE.getKey().getTextLayoutList())?pageNum:TZJE.getKey().getTextLayoutList().get(0).getPageNumber();
                        ComponentResult zjgc = getComponentResult(false,"01","在建工程检查（"+projectName+"）",_pageNum,"投资金额存在",getRuleTitle(),getContentAndPositionList(TZJE.getKey().getTextLayoutList()));
                        list.add(zjgc);
                    }
                    if(YTZJE==null || YTZJE.getKey()==null || StringUtils.isEmpty(YTZJE.getKey().getText())){
                        ComponentResult zjgc = getComponentResult(true,"02","在建工程检查（"+projectName+"）",pageNum,"已投资金额缺失",getRuleTitle(),null);
                        list.add(zjgc);
                    }else{
                        int _pageNum = CollectionUtils.isEmpty(YTZJE.getKey().getTextLayoutList())?pageNum:YTZJE.getKey().getTextLayoutList().get(0).getPageNumber();
                        ComponentResult zjgc = getComponentResult(true,"01","在建工程检查（"+projectName+"）",_pageNum,"已投资金额存在",getRuleTitle(),getContentAndPositionList(YTZJE.getKey().getTextLayoutList()));
                        list.add(zjgc);
                    }
                    if(ZBJ==null || ZBJ.getKey()==null || StringUtils.isEmpty(ZBJ.getKey().getText())){
                        ComponentResult zjgc = getComponentResult(true,"02","在建工程检查（"+projectName+"）",pageNum,"资本金缺失",getRuleTitle(),null);
                        list.add(zjgc);
                    }else{
                        int _pageNum = CollectionUtils.isEmpty(ZBJ.getKey().getTextLayoutList())?pageNum:ZBJ.getKey().getTextLayoutList().get(0).getPageNumber();
                        ComponentResult zjgc = getComponentResult(true,"01","在建工程检查（"+projectName+"）",_pageNum,"资本金存在",getRuleTitle(),getContentAndPositionList(ZBJ.getKey().getTextLayoutList()));
                        list.add(zjgc);
                    }
                    if(HGX==null || HGX.getKey()==null || StringUtils.isEmpty(HGX.getKey().getText())){
                        ComponentResult zjgc = getComponentResult(true,"02","在建工程检查（"+projectName+"）",pageNum,"合规性缺失",getRuleTitle(),null);
                        list.add(zjgc);
                    }else{
                        int _pageNum = CollectionUtils.isEmpty(HGX.getKey().getTextLayoutList())?pageNum:HGX.getKey().getTextLayoutList().get(0).getPageNumber();
                        ComponentResult zjgc = getComponentResult(true,"01","在建工程检查（"+projectName+"）",_pageNum,"合规性存在",getRuleTitle(),getContentAndPositionList(HGX.getKey().getTextLayoutList()));
                        list.add(zjgc);
                    }
                    if(TZJE!=null){
                        if(TZJE.getValue()!=null){
                            double TZJEd = getDouble(TZJE.getValue().getText());
                            if(TZJEd/ZTZJE>0.1){
                                ZJGCMap.put(projectName,TZJEd/ZTZJE+"");
                            }
                        }
                    }
                }
            }
        }else{
            //在建工程不存在
            ComponentResult zjgc = getComponentResult(true,"02","在建工程检查",0,"缺失",getRuleTitle(),null);
            list.add(zjgc);
        }
        List<ComponentResult> li = getList(ZJGCMap);
        list.addAll(li);
        if(CollectionUtils.isEmpty(list)){
            ComponentResult result = getComponentResult(true,"02","在建工程检查",pageNum,"未抽取到数据",getRuleTitle(),null);
            list.add(result);
        }
        list.add(getNJGC(getExtractData(),catalogId));
        return list;
    }


    private List<ComponentResult> getList(Map<String,String> kmMap){
        List<ComponentResult> list = new ArrayList<>();
        for(String bk : kmMap.keySet()){
            boolean exist = false;
            int pageNum = getChapterModel(getCatalogId()).getStartPage();
            List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
            try{

                for(int j=0;j<getChapterModel(getCatalogId()).getPageModelList().size();j++){
                    PageModel pageModel = getChapterModel(getCatalogId()).getPageModelList().get(j);
                    if(exist) break;
                    Map page = new HashMap();
                    pageNum = pageModel.getPageNumber();
                    JsonArray jsonTextDataArray = pageModel.getJsonTextData()!=null?pageModel.getJsonTextData().getAsJsonArray():null;
                    if(jsonTextDataArray!=null) {
                        for (JsonElement element : jsonTextDataArray) {
                            if(exist) break;
                            JsonArray data = element.getAsJsonObject() != null ? element.getAsJsonObject().getAsJsonArray("data") : null;//当页文本
                            if (data != null) {
                                for(int i=0;i<data.size();i++){
                                    if(exist) break;
                                    JsonObject current = returnOne(data.get(i).getAsJsonArray());
                                    String content = current.get("text").getAsString();
                                    if(Pattern.matches("\\d{1,2}、"+bk+"[\\S\\s]*",content)){
                                        exist = true;
                                        page.put("pageNum",pageNum);page.put("lineNum",i);
                                        double x = current.get("left").getAsDouble();
                                        double y = current.get("top").getAsDouble();
                                        ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                                        textPosition.setContent(content);
                                        textPosition.setX(x);
                                        textPosition.setY(y);
                                        textPositionList.add(textPosition);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if(exist){
                        if(jsonTextDataArray!=null) {
                            for (JsonElement element : jsonTextDataArray) {
                                JsonArray data = element.getAsJsonObject() != null ? element.getAsJsonObject().getAsJsonArray("data") : null;//当页文本
                                Result result = getTextPositionList(data,page,pageModel,j);
                                List<ComponentResult.TextPosition> _textPositionList = result.getList();
//                                textPositionList.addAll(_textPositionList);
                                boolean boo = result.isBoo();
                                if(!boo && _textPositionList.size()<3){
                                    int lines = _textPositionList.size();
                                    if(j<=getChapterModel(getCatalogId()).getPageModelList().size()-2){//连续判断下一页
                                        PageModel _pageModel = getChapterModel(getCatalogId()).getPageModelList().get(j+1);
                                        JsonArray _jsonTextDataArray = _pageModel.getJsonTextData()!=null?_pageModel.getJsonTextData().getAsJsonArray():null;
                                        if(_jsonTextDataArray!=null){
                                            List<ComponentResult.TextPosition> _list = new ArrayList<>();
                                            for (JsonElement _element : _jsonTextDataArray) {
                                                JsonArray _data = _element.getAsJsonObject() != null ? _element.getAsJsonObject().getAsJsonArray("data") : null;//当页文本
                                                page.put("pageNum",pageNum+1);page.put("lineNum",0);
                                                Result _result = getTextPositionList(_data,page,_pageModel,j);
                                                List<ComponentResult.TextPosition> __textPositionList = _result.getList();
                                                lines += __textPositionList.size();
                                                _list.addAll(__textPositionList);
                                            }
                                            if(lines<3){
                                                exist = false;
                                            }else{
//                                                textPositionList.addAll(_list);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
            ComponentResult result = getComponentResult(!exist,exist?"01":"02","在建工程-"+bk,pageNum,exist?("在建工程（"+bk+"）项目建设情况介绍符合要求"):("在建工程（"+bk+"）项目建设情况介绍不符合要求"),getRuleTitle(),textPositionList);
            list.add(result);
        }
        return list;
    }

    private Result getTextPositionList(JsonArray data, Map page, PageModel pageModel, int j){
        Result result = new Result();
        List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
        if (data != null) {
            List<ComponentResult.TextPosition> _textPositionList = new ArrayList<>();
            for(int i=(int)page.get("lineNum")+1;i<data.size();i++){
                JsonObject current = returnOne(data.get(i).getAsJsonArray());
                String content = current.get("text").getAsString();
                double x = current.get("left").getAsDouble();
                double y = current.get("top").getAsDouble();
                ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                textPosition.setContent(content);
                textPosition.setX(x);
                textPosition.setY(y);
                _textPositionList.add(textPosition);
                if(Pattern.matches("\\d{1,2}、[\\S\\s]*",content) || Pattern.matches("图表[\\S\\s]*",content)){//到下一章节
                    if(i-(int)page.get("lineNum")>=5){
                        _textPositionList.remove(_textPositionList.size()-1);
                        result.setBoo(true);
                        break;
                    }
                }else if(data.size()-(int)page.get("lineNum")>=3 && i==data.size()-1){//到当前页最后
                    result.setBoo(true);
                    break;
                }else{
                    result.setBoo(false);
                }
            }
            textPositionList.addAll(_textPositionList);
        }
        result.setList(textPositionList);
        return result;
    }

    public class Result{
        private List<ComponentResult.TextPosition> list;
        private boolean boo;

        public List<ComponentResult.TextPosition> getList() {
            return list;
        }

        public void setList(List<ComponentResult.TextPosition> list) {
            this.list = list;
        }

        public boolean isBoo() {
            return boo;
        }

        public void setBoo(boolean boo) {
            this.boo = boo;
        }
    }


    /**
     * @auth 佟媛媛
     * @date 18/11/3 下午5:25
     * @desc 拟建工程判断
     */
    private ComponentResult getNJGC(DocumentModel model,String catalogId){
        String exist = "02";
        int pageNum = getChapterModel(getCatalogId()).getStartPage();
        String promptMsg = "缺失";
        boolean annotationFlag = true;
        List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
        i1001.setExtractData(model);
        i1001.setCatalogId(catalogId);
        i1001.setKeyword("拟建工程");
        Map njMap = i1001.ifKeywordExist2(getCatalogId());
        boolean _exist = (boolean)njMap.get("exist");
        if(_exist){
            exist = "01";
            promptMsg = "正确";
            annotationFlag = false;
            List<ContentAndPosition> contentAndPositionList = (List<ContentAndPosition>) njMap.get("contentAndPositionList");
            if(!CollectionUtils.isEmpty(contentAndPositionList)){
                for(ContentAndPosition contentAndPosition : contentAndPositionList){
                    pageNum = contentAndPosition.getPageNum();
                    ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                    textPosition.setX(contentAndPosition.getX());
                    textPosition.setY(contentAndPosition.getY());
                    textPosition.setContent(contentAndPosition.getContent());
                    textPositionList.add(textPosition);
                }
            }
        }
        ComponentResult njgc = getComponentResult(annotationFlag,exist,"拟建工程检查",pageNum,promptMsg,getRuleTitle(),textPositionList);
        return njgc;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        return common("BM-5");
    }

    @Override
    public List<ComponentResult> handlerDM() {
        return common("DM-5");
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        return common("BDM-5");
    }


    private ComponentResult getComponentResult(boolean annotationFlag,String exist,String keyword,int pageNum,String promptMsg,String ruleName,List<ComponentResult.TextPosition> textPositionList){
        ComponentResult result = new ComponentResult();
        result.setAnnotationFlag(annotationFlag);
        result.setCatalogId(getCatalogId());
        result.setChapterId(getChapterId());
        result.setExist(exist);
        result.setKeyword(keyword);
        result.setPageNum(pageNum);
        result.setPromptMessage(promptMsg);
        result.setRegulationId(getRegulationId());
        result.setRuleName(ruleName);
        result.setTextPosition(textPositionList);
        result.setUid(UUID.randomUUID().toString());
        return result;
    }

}
